// PollServer.hpp
#pragma once

#include <iostream>
#include <poll.h>
#include "TcpSocket.hpp"
using namespace std;

static const uint16_t defaultport = 8080; // 缺省端口号
static const int fd_num_max = 64;         // pollfd数组的元素个数
int defaultfd = -1;                       // 缺省文件描述符值
int non_event = 0;                        // events和revents初始化用

class PollServer
{
public:
    PollServer(uint16_t port = defaultport)
        : _port(port)
    {
        for (int i = 0; i < fd_num_max; ++i)
        {
            _event_fds[i].fd = defaultfd;
            _event_fds[i].events = non_event;
            _event_fds[i].revents = non_event;
        }
    }
    ~PollServer()
    {
        _listensock.Close();
        delete[] _event_fds;
    }
    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();

        return true;
    }
    void Start()
    {
        _event_fds[0].fd = _listensock.getfd();
        _event_fds[0].events = POLLIN;
        int timeout = 1000;

        for (;;)
        {
            int n = poll(_event_fds, fd_num_max, timeout);

            switch (n)
            {
            case 0:
                cout << "time out..." << endl;
                break;
            case -1:
                cerr << "poll error" << endl;
                break;
            default:
                // 有事件就绪了，TODO
                Dispatcher(); // 事件派发器
                break;
            }
        }
    }
    void Dispatcher()
    {
        for (int i = 0; i < fd_num_max; ++i) // 第三个循环
        {
            int fd = _event_fds[i].fd;
            if (fd == defaultfd)
                continue;

            if (_event_fds[i].revents & POLLIN)
            {
                if (fd == _listensock.getfd())
                {
                    // 连接事件就绪了
                    Accepter(); // 连接管理器
                }
                else // non listensock
                {
                    // 读事件就绪
                    Recver(fd, i);
                }
            }
        }
    }
    void Accepter()
    {
        cout << "get a new link!!!" << endl;
        string clientip;
        uint16_t clientport;
        int sockfd = _listensock.Accept(&clientip, &clientport); // 会不会阻塞呢？不会
        if (sockfd < 0)
            return;
        lg(Info, "accept success, %s, %d, sockfd: %d", clientip.c_str(), clientport, sockfd);

        // 我们并不清楚，sockfd的读事件是否就绪，所以不能直接read，而是要把它添加进_event_fds里
        int pos = 1;
        for (; pos < fd_num_max; ++pos) // 第二个循环
        {
            if (_event_fds[pos].fd == defaultfd)
                break;
        }
        if (pos == fd_num_max)
        {
            lg(Warning, "server is full, close %d now", sockfd);
            close(sockfd);
            // _event_fds满了，select里直接关闭sockfd
            // poll里可以选择进行扩容，也可以直接把它定义成一个很大的数组，本来它就是一个高频使用的数组
        }
        else
        {
            _event_fds[pos].fd = sockfd;
            _event_fds[pos].events = POLLIN;
            PrintFd(); // 测试
        }
    }
    void Recver(int fd, int pos)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1); // bug: 无法保证读上来的是一个完整的报文
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "get a message: " << buffer << endl;
        }
        else if (n == 0)
        {
            // 对方把文件描述符关了，我这边读到了结尾，所以要关闭fd
            lg(Info, "client quit, me too. close fd %d", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd; // 并在读辅助数组中移除fd，本质是在select中移除fd
        }
        else
        {
            // 读出错
            lg(Warning, "recv error, close fd %d", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd; // 并在读辅助数组中移除fd，本质是在select中移除fd
        }
    }
    void PrintFd()
    {
        cout << "online rfd list: ";
        for (int i = 0; i < fd_num_max; ++i)
        {
            if (_event_fds[i].fd != defaultfd)
            {
                cout << _event_fds[i].fd << " ";
            }
        }
        cout << endl;
    }

private:
    TcpSocket _listensock;
    uint16_t _port;
    // struct pollfd _event_fds[fd_num_max];
    struct pollfd *_event_fds = new struct pollfd[fd_num_max];
};